<?php

namespace Home\Controller;

/**
 * 房间ajax接口
 * @modify zhangzhen 2017-03-24 创建
 */
class HourRoomController extends \Home\Controller\ParentController {
    protected $hotelId;

    protected function _initialize() {
        parent::_initialize();
        $this->validateUtil = new \Org\Util\Validate();

        //检查操作权限
        $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
        $this->hotelId = I('post.hotel');
        $adminAuthorityLogic->check($this->hotelId);
    }

    /**
     * 获取房型与房间
     * @add zhangzhen 2017-3-24 创建
     */
    public function getRoomList() {
        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }
        // TOOD:添加权限校验,暂时只有超级管理员可以访问
        
        $roomLogic = A('Common/Room', 'Logic');
        $returnData = $roomLogic->getHourRoomList($this->hotelId);
        returnJson(200, 200, $returnData);
    }

    /**
     * 初始化钟点房
     * @add zhangzhen 2017-3-27 创建
     */
    public function initHourRoom() {
        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'checkinTime' => 'notnull,notempty,isHour_G',
            'checkoutTime' => 'notnull,notempty,isHour_G',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }
        $hotelId = $param['hotel'];
        $checkinTime = $param['checkinTime'];
        $checkoutTime = $param['checkoutTime'];
        $hourRoomInitModel = D('HourRoomInit');
        $result = $hourRoomInitModel->addInfo($hotelId, $checkinTime, $checkoutTime);
        if ($result) {
            returnJson(200, 200, $result);
        } else {
            returnJson(500, 508);
        }
    }
    /**
     * 初始化钟点房
     * @add zhangzhen 2017-3-27 创建
     */
    public function getHourRoomInit() {
        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }
        $hotelId = $param['hotel'];
        $hourRoomLogic = A('Common/HourRoom', 'Logic');
        $hourRoomInfos = $hourRoomLogic->getInfosByHotel($hotelId);
        returnJson(200, 200, $hourRoomInfos);
    }

     /**
     * 添加钟点房
     * @add zhangzhen 2017-5-15 创建
     */
    public function addHourRoom() {
        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'price' => 'notnull,notempty',
            'roomInfoIds' => 'notnull,notempty',
            'roomTypeId' => 'notnull,notempty,id',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }
        $hotel = $param['hotel'];
        $price = $param['price'];
        $roomInfoIds = $param['roomInfoIds'];
        $roomTypeId = $param['roomTypeId'];
        $userId = getUserId();
        $dataList = [];
        foreach ($roomInfoIds as $key => $roomInfoId) {
            $dataList[$key]['hotelentity_id'] = $hotel;
            $dataList[$key]['roominfo_id'] = $roomInfoId;
            $dataList[$key]['roomtype_id'] = $roomTypeId;
            $dataList[$key]['creator'] = $userId;
            $dataList[$key]['operator'] = $userId;
        }
        unset($roomInfoId);
        $hourRoomModel = D('HourRoom');
        $hourRoomModel->startTrans();
        $commit = true;
        $result = $hourRoomModel->addAllInfos($dataList);
        if ($result === false) {
            $commit = false;
        }
        if ($commit === true) {
            $dataList = [];
            foreach ($price as $key => $one) {
                $dataList[$key]['hotelentity_id'] = $hotel;
                $dataList[$key]['roomtype_id'] = $roomTypeId;
                $dataList[$key]['hour'] = $key*2+2;
                $dataList[$key]['price'] = $one;
            }
            unset($one);
            $hourPriceModel = D('HourPrice');
            $result = $hourPriceModel->addAllInfos($dataList);
            if ($result === false) {
                $commit = false;
            } 
        }
        
        if ($commit === true) {
            $roomTypeModel = D('RoomType');
            $result = $roomTypeModel->saveHourRoomPriceId($roomTypeId);
            if ($result === false) {
                $commit = false;
            }
        }
        

        if ($commit === false) {
            $hourRoomModel->rollback();
            returnJson(500, 508); 
        } else {
            $hourRoomModel->commit();
            $hourRoomLogic = A('Common/HourRoom', 'Logic');
            $hourRoomInfos = $hourRoomLogic->getInfosByHotel($hotel);
            returnJson(200, 200, $hourRoomInfos);
        }
        
    }

    /**
     * 获取钟点房
     * @add zhangzhen 2017-5-15 创建
     */
    public function getRoomByTypeId() {
        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'roomTypeId' => 'notnull,notempty,id',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }
        $roomTypeId = $param['roomTypeId'];
        $roomInfoModel = D('RoomInfo');
        $roomInfos = $roomInfoModel->getRoomByTypeId($roomTypeId);
        $hourPriceModel = D('HourPrice'); 
        $hourPrice = $hourPriceModel->getInfoByRoomType($roomTypeId);
        returnJson(200, 200, ['roomInfos' => $roomInfos, 'hourPrice' => $hourPrice]);
    }

    /**
     * 修改钟点房
     * @add zhangzhen 2017-5-16 创建
     */
    public function saveHourRoom() {
        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'waitForDelete' => 'notempty',
            'waitForAdd' => 'notempty',
            'roomTypeId' => 'notnull,notempty,id',
            'price' => 'notnull,notempty',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }
        $hotel = $param['hotel'];
        $roomTypeId = $param['roomTypeId'];
        $price = $param['price'];
        $userId = getUserId(); 

        // 获取客栈默认符号
        $symbol = $this->getDefultCurrencyByHotel($hotel);

        $hourPriceModel = D('HourPrice');
        $hourPrices = $hourPriceModel->getPriceByRoomType($roomTypeId);
        $hourPrices = getArrayValueAsIndex($hourPrices,'hour');
        $hourPriceModel->startTrans();
        $commit = true;
        $priceLogMap = array(
            'zh_cn' => '小时价格设置为' . $symbol,
            'en_us' => 'hour set price ' . $symbol,
            'zh_tw' => '小時價格設置为' . $symbol,
        );
        foreach ($price as $key => $one) {
            $hour = $key * 2 + 2;
            if ($hourPrices[$hour]['price'] != $one){
                $result = $hourPriceModel->saveInfoByRoomTypeAndHour($roomTypeId, $hour, $one);
                if ($result === false) {
                    $commit = false;
                    break;
                }
                priceChangeLog($hotel, $roomTypeId, $hour. $priceLogMap[LANG_SET] . $one, strtotime(date('Y-m-d')), '', HOUR_PRICE, '');
            }
        }
        unset($one);
        if ($commit === true) {
            $hourRoomModel = D('HourRoom');
            if(isset($param['waitForDelete'],$param['waitForAdd'])){
                $waitForDelete = $param['waitForDelete'];
                $waitForAdd = $param['waitForAdd'];
                $tempAdd = array_diff($waitForAdd,$waitForDelete);
                $waitForDelete = array_diff($waitForDelete,$waitForAdd);
                $waitForAdd = $tempAdd;
            }

            if (isset($param['waitForDelete'])) {
                $waitForDelete = isset($waitForDelete) ? $waitForDelete : $param['waitForDelete'];
                $waitForDelete = implode(',', $waitForDelete);
                $orderRoomModel = D('OrderRoom');
                // 检查房间是否有活跃状态订单
                $orderInfo = $orderRoomModel->getInfoByHotelRoom($hotel, $waitForDelete);
                // 无效订单无法阻止房间删除
                foreach ($orderInfo as $index => $orderItem) {
                    if (in_array($orderItem['status'], array(ORDER_CHECKOUTED, ORDER_CANCELED, ORDER_OUTDATED)) || $orderItem['realnight'] > 0) {
                        unset($orderInfo[$index]);
                    }
                }
                unset($orderItem);
                if(!empty($orderInfo)) {
                    $hourPriceModel->rollback();
                    returnJson(403, 300, 'error');
                }
                $result = $hourRoomModel->deleteInfosInIds($waitForDelete);
            } 

            if (isset($param['waitForAdd'])) {
                $waitForAdd = isset($waitForAdd) ? array_values($waitForAdd) : array_values($param['waitForAdd']);
                $dataList = [];
                foreach ($waitForAdd as $key => $roomInfoId) {
                    $dataList[$key]['hotelentity_id'] = $hotel;
                    $dataList[$key]['roominfo_id'] = $roomInfoId;
                    $dataList[$key]['roomtype_id'] = $roomTypeId;
                    $dataList[$key]['creator'] = $userId;
                    $dataList[$key]['operator'] = $userId;
                }
                $result = $hourRoomModel->addAllInfos($dataList);
                if ($result === false) {
                    $commit = false;
                }
            }
        }
        if ($commit === false) {
            $hourPriceModel->rollback();
            returnJson(500, 508); 
        } else {
            $hourPriceModel->commit();
            $hourRoomLogic = A('Common/HourRoom', 'Logic');
            $hourRoomInfos = $hourRoomLogic->getInfosByHotel($hotel);
            returnJson(200, 200, $hourRoomInfos);
        }
    }

    /**
     * 修改钟点房
     * @add zhangzhen 2017-5-16 创建
     */
    public function deleteHourRoom() {
        $param = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,id',
            'roomTypeId' => 'notnull,notempty,id',
        );
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (empty($validatePass)) {
            return;
        }
        $hotel = $param['hotel'];
        $roomTypeId = $param['roomTypeId'];

        $hourRoomModel = D('HourRoom');
        $hourRoomInfos = $hourRoomModel->getInfosByRoomType($roomTypeId);
        $roomIds = array_column($hourRoomInfos, 'roominfo_id');

        $orderRoomModel = D('OrderRoom');
        // 检查房间是否有活跃状态订单
        $orderInfo = $orderRoomModel->getInfoByHotelRoom($hotel, $roomIds);
        // 无效订单无法阻止房间删除
        foreach ($orderInfo as $index => $orderItem) {
            if (in_array($orderItem['status'], array(ORDER_CHECKOUTED, ORDER_CANCELED, ORDER_OUTDATED)) || $orderItem['realnight'] > 0) {
                unset($orderInfo[$index]);
            }
        }
        unset($orderItem);
        if(!empty($orderInfo)) {
            returnJson(403, 300, 'error');
        }
        $hourRoomModel->startTrans();
        $commit = true;
        $result = $hourRoomModel->deleteInfoByTypeId($roomTypeId);
        if (! $result) {
            $commit = false;
        }
        if ($commit) {
            $roomTypeModel = D('RoomType');
            $result = $roomTypeModel->saveHourRoomPriceId($roomTypeId, 0);
            if (! $result) {
                $commit = false;
            }
        }
        if ($commit) {
            $hourPriceModel = D('HourPrice');
            $result = $hourPriceModel->deleteInfoByTypeId($roomTypeId);
            if (! $result) {
                $commit = false;
            }
        }
        if ($commit) {
            $hourRoomModel->commit();
            $hourRoomLogic = A('Common/HourRoom', 'Logic');
            $hourRoomInfos = $hourRoomLogic->getInfosByHotel($hotel);
            returnJson(200, 200, $hourRoomInfos);
        } else {
            $hourRoomModel->rollback();
            returnJson(500, 510);
        }
        
    }

}
